package com.ruoyi.SuveryInterface.NegativeSuvery;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.lang.StringUtils;
import sun.misc.BASE64Decoder;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;

/**
 * AES 的加密和解密
 */
public class AES {
    //密钥 (需要前端和后端保持⼀致)
    private static final String KEY = "1234567890ABCDEf";
    //算法
    private static final String ALGORITHMSTR = "AES/ECB/PKCS5Padding";


    public static String base64Encode(byte[] bytes) {
        return Base64.encodeBase64String(bytes);
    }


    public static byte[] base64Decode(String base64Code) throws Exception {
        return StringUtils.isNotEmpty(base64Code) ? new BASE64Decoder().decodeBuffer(base64Code) : null;
    }

    public static byte[] aesEncryptToBytes(String content, String encryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.ENCRYPT_MODE, new
                SecretKeySpec(encryptKey.getBytes(), "AES"));
        return cipher.doFinal(content.getBytes("utf-8"));
    }

    public static String aesEncrypt(String content, String encryptKey) throws
            Exception {
        return base64Encode(aesEncryptToBytes(content, encryptKey));
    }


    public static String aesDecryptByBytes(byte[] encryptBytes, String
            decryptKey) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance("AES");
        kgen.init(128);
        Cipher cipher = Cipher.getInstance(ALGORITHMSTR);
        cipher.init(Cipher.DECRYPT_MODE, new
                SecretKeySpec(decryptKey.getBytes(), "AES"));
        byte[] decryptBytes = cipher.doFinal(encryptBytes);
        return new String(decryptBytes);
    }

    public static String aesDecrypt(String encryptStr, String decryptKey) throws Exception {
        return StringUtils.isNotEmpty(encryptStr) ?
                aesDecryptByBytes(base64Decode(encryptStr), decryptKey) : null;
    }

}
